package com.guli.pay.service;


import com.github.wxpay.sdk.WXPayUtil;

import com.guli.pay.mapper.PaymentInfoEntityMapper;
import com.guli.pay.until.Result;
import okhttp3.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WXPayService {

    @Autowired
    PaymentInfoEntityMapper paymentInfoEntityMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Value("${weixin.appid}")
    String appid;
    @Value("${weixin.partner}")
    String partner;
    @Value("${weixin.partnerkey}")
    String partnerkey;
    @Value("${weixin.notifyurl}")
    String notifyurl;


    /**
     *调用微信支付接口
     * @param orderId
     * @param totalFee
     * @param body
     * @return
     */
    public Result unifiedOrder(Long orderId, Integer totalFee, String body) throws Exception {
        //发送请求
        String url="https://api.mch.weixin.qq.com/pay/unifiedorder";
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();//POSTman
        Map map= new HashMap<>();
        map.put("appid",appid);
        map.put("mch_id",partner);
        map.put("nonce_str", WXPayUtil.generateNonceStr());
        map.put("total_fee",String.valueOf(totalFee));
        map.put("spbill_create_ip","127.0.0.1");
        map.put("notify_url",notifyurl);
        map.put("trade_type","NATIVE");
        map.put("out_trade_no",String.valueOf(orderId));
        map.put("body", body);

        String sign = WXPayUtil.generateSignature(map, partnerkey);
        map.put("sign",sign);
        String requestBodyXml = WXPayUtil.mapToXml(map);
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/xml"),
                requestBodyXml
        );
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type","application/xml")
                .post(requestBody)
                .build();


        //点击发送
        Response execute = okHttpClient.newCall(request).execute();
        System.out.println("successful="+execute.isSuccessful());
        System.out.println("code="+execute.code());
        System.out.println("message ="+ execute.message());
        System.out.println("headers ="+ execute.headers());


        String responseBody_xml = execute.body().string();
        System.out.println(responseBody_xml);
        Map<String, String> stringStringMap = WXPayUtil.xmlToMap(responseBody_xml);
        String return_code = stringStringMap.get("return_code");
        String return_msg = stringStringMap.get("return_msg");
        if(return_code.equalsIgnoreCase("SUCCESS")){
            String result_code = stringStringMap.get("result_code");
            if(result_code.equalsIgnoreCase("SUCCESS")){
                String code_url = stringStringMap.get("code_url");
                return new Result(true,"1",code_url);
            }
        }


        return new Result(false,"0",return_msg);

    }

    /**
     * 获取微信订单信息，查看状态
     * @param orderId
     * @return
     * @throws Exception
     */
    public Result orderQuery(Long orderId) throws Exception {


        OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();

        Map map=  new HashMap<>();
        map.put("appid",appid);
        map.put("mch_id",partner);
        map.put("out_trade_no",String.valueOf(orderId));
        map.put("nonce_str",WXPayUtil.generateNonceStr());


        String sign = WXPayUtil.generateSignature(map, partnerkey);
        map.put("sign",sign);
        String requestBodyXml = WXPayUtil.mapToXml(map);
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/xml"),
                requestBodyXml
        );
        Request request = new  Request.Builder()
                .url("https://api.mch.weixin.qq.com/pay/orderquery")
                .post(requestBody)
                .build();

        Response response = okHttpClient.newCall(request).execute();
        System.out.println("successful = " + response.isSuccessful());
        System.out.println("code = " + response.code());//200
        System.out.println("message = " + response.message());//OK
        System.out.println("headers = " + response.headers());

        String responseBody_xml = response.body().string();

        System.out.println(responseBody_xml);
        Map<String, String> responseBodyMap = WXPayUtil.xmlToMap(responseBody_xml);
        String return_code = responseBodyMap.get("return_code");
        String return_msg = responseBodyMap.get("return_msg");
        if(return_code.equalsIgnoreCase("SUCCESS")){
            String result_code = responseBodyMap.get("result_code");
            if(result_code.equalsIgnoreCase("SUCCESS")){
                /*
                SUCCESS--支付成功
                REFUND--转入退款
                NOTPAY--未支付
                CLOSED--已关闭
                REVOKED--已撤销(刷卡支付)
                USERPAYING--用户支付中
                PAYERROR--支付失败(其他原因，如银行返回失败)
                ACCEPT--已接收，等待扣款
                 */
                String trade_state = responseBodyMap.get("trade_state");
                String trade_state_desc =responseBodyMap.get("trade_state_desc");
                String total_fee =responseBodyMap.get("total_fee");

                if(trade_state.equalsIgnoreCase("SUCCESS")){//支付成功
                    //paySuccess(orderId,Integer.valueOf(total_fee));
                    return  new Result(true,"1",trade_state_desc);
                }

                return  new Result(false,"0",trade_state_desc);
            }else{
                String err_code_des = responseBodyMap.get("err_code_des");
                return  new Result(false,"0",err_code_des);
            }
        }
        return  new Result(false,"0",return_msg);
    }


//    private  void paySuccess(Long orderId,Integer totalFee ){
//        //插入一条支付记录
//        QueryWrapper<PaymentInfoEntity> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(PaymentInfoEntity::getOrderId,orderId);
//        List<PaymentInfoEntity> paymentInfoEntities = paymentInfoEntityMapper.selectList(queryWrapper);
//        if(paymentInfoEntities.size()==0){//不存在该订单 支付记录
//            PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
//            paymentInfoEntity.setOrderId(orderId);
//            paymentInfoEntity.setTotalAmount(new BigDecimal(totalFee * 1.0 / 100));
//            paymentInfoEntity.setCreateTime(new Date());
//            paymentInfoEntityMapper.insert(paymentInfoEntity);
//
//
//            //2、加积分 用户微服务
//            //3、修改 订单状态
//            //4 修改锁定库存
//            Map map=  new HashMap<>();
//            map.put("orderId",orderId);
//            map.put("payType",301);
//            map.put("status","SUCCESS");
//
//            rabbitTemplate.convertAndSend("exchange_fanout_paySuccess",
//                    (message)->{
//                        message.getMessageProperties().setMessageId(String.valueOf(orderId));
//                        return message;
//                    });
//
//        }
//    }
}
